package com.example.demo.ding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;

/**
 * @Author: zjq
 * @Date: create in 2022/10/8 14:23
 */
public class DingUtil {

    //企业凭证，两小时一更新
    private static String accessToken = null;
    //媒体文件ID，引用的媒体文件最大10MB
    private static String mediaId = null;
    //钉钉用户id
    private static String userId = null;
    //应用凭证---测试用
    //private static String appkey = "ding1duybr8gaocmpygq";
    //private static String appsecret = "QJnjbvClXGtQkpGhcV5PfiN_TyfsJ1NgOClDjWQI2y7j7NwvMmly6Ov33vrwE5nw";
    //private static Long AgentId = 1936838885L;

    //获取token,每两小时失效
    public static String gettoken(String appkey,String appsecret) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appkey);
            req.setAppsecret(appsecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            System.out.println("token:" + rsp.getBody());
            JSONObject json = JSON.parseObject(rsp.getBody());
            accessToken = json.getString("access_token");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    //向钉钉推送文件
    public static String sendFile(String filePath) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
            OapiMediaUploadRequest req = new OapiMediaUploadRequest();
            req.setType("file");
            // 要上传的媒体文件
            FileItem item = new FileItem(filePath);
            req.setMedia(item);
            OapiMediaUploadResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());

            JSONObject json = JSON.parseObject(rsp.getBody());
            mediaId = json.getString("media_id");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return mediaId;
    }

    //钉钉推送消息
    public static void sendMessage(String dingUserId,Long AgentId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(AgentId);//发送消息时使用的微应用的AgentID
            request.setUseridList(dingUserId);//接收者的userid列表
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

            msg.setMsgtype("file");
            msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
            msg.getFile().setMediaId(mediaId);
            request.setMsg(msg);

            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    //根据手机号查询用户id
    public static String getUserid(String mobile) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());

            JSONObject json = JSON.parseObject(rsp.getBody());
            if ("0".equals(json.getString("errcode"))) {
                userId = json.getJSONObject("result").getString("userid");
            } else {
                userId = null;
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return userId;
    }


}
